# -*- coding: utf-8 -*-
import json
from pyquery import PyQuery
from zc_core.model.items import *
from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.util.common import parse_number
from zc_core.util.sku_id_parser import convert_id2code
from zc_core.util.encrypt_util import md5
from zc_core.model.items import ItemDataSupply


def parse_catalog(response):
    if not response.text:
        return None
    cats = list()

    docs = PyQuery(response.text)
    cats_1 = docs("body h3").items()
    for cat_1 in cats_1:
        cat1_name = cat_1("a").text()
        entity1 = build_catalog(md5(cat1_name), cat1_name, 1)
        cats.append(entity1)
        cat1_childs = cat_1.parent("div")("dl").items()
        if cat1_childs:
            for cat1_child in cat1_childs:
                cat_2 = cat1_child("dt")
                cat2_name = cat_2("a").text()
                entity2 = build_catalog(md5(cat2_name), cat2_name, 2, md5(cat1_name))
                cats.append(entity2)
                cats_3 = cat1_child("dd").items()
                for cat3 in cats_3:
                    cat3_name = cat3("a").text()
                    cat3_id = cat3("a").attr("href").split("?cid=")[1].split("&")[0]
                    entity3 = build_catalog(cat3_id, cat3_name, 3, md5(cat2_name))
                    cats.append(entity3)

    return cats


def build_catalog(id, name, level, parent_id=None):
    entity = Catalog()

    entity['catalogId'] = id
    entity['catalogName'] = name
    entity['parentId'] = parent_id
    entity['level'] = level
    if entity['level'] == 3:
        entity['leafFlag'] = 1
    else:
        entity['leafFlag'] = 0
    entity['linkable'] = 0
    return entity


def parse_sku(response):
    if not response.text:
        return None
    sku_list = json.loads(response.text)
    meta = response.meta
    batch_no = meta.get('batchNo')
    skus = list()
    for sku in sku_list:
        entity = Sku()
        entity['batchNo'] = batch_no
        entity['skuId'] = str(sku.get("goodsId"))
        entity['supplierId'] = str(sku.get("id"))
        entity['catalog3Id'] = str(sku.get("classId"))
        entity['catalog3Name'] = sku.get("className")
        skus.append(entity)
    return skus


def parse_item_data(response):
    if not response.text:
        return None
    meta = response.meta
    batch_no = meta.get('batchNo')
    catalog3_id=meta.get('catalog3Id')
    sku_doc = PyQuery(response.text)
    sku_id = sku_doc("input#goodsid").val()
    sku_name = sku_doc("input#goodsname").val()
    if not sku_doc("input#goodsPrice").val():
        return None
    sale_price = parse_number(sku_doc("input#goodsPrice").val())
    origin_price = parse_number(sku_doc("span#checkGoodsSpecIntPrice").text(), sale_price)
    supplier_id = sku_doc("input#supplierId").val()
    supplier_name = sku_doc("input#supplierName").val()
    sku_img = sku_doc(".jqzoom img").attr('src')
    spu_id = sku_doc("input#goodsSpu").val()
    sp_sku_id = sku_doc("input#goodsSku").val()
    sales = sku_doc(".J-comm-1855935").eq(1).text()
    stock = sku_doc("input#goodsStock").val() or 0

    item = ItemData()
    item['batchNo'] = batch_no

    item['skuId'] = str(sku_id)
    item['skuName'] = sku_name
    item['originPrice'] = origin_price
    item['salePrice'] = sale_price
    item['skuImg'] = sku_img
    item['supplierId'] = str(supplier_id)
    item['supplierName'] = supplier_name

    item['spuId'] = str(spu_id)
    if sales:
        item['soldCount'] = parse_number(sales[0:-1])
    if stock:
        item['stock'] = parse_number(stock)

    # item['brandId'] = str(item_data.get("brandId"))
    # item['brandModel'] = item_data.get("model")
    # item['brandName'] = item_data.get("brandName")

    catalog1_name = sku_doc('.breadcrumb strong').text().strip()
    item['catalog1Name'] = catalog1_name
    item['catalog1Id'] = md5(catalog1_name + ":1")
    catalogs_list = [x.text().replace('>\xa0', '').strip() for x in sku_doc('.breadcrumb span').items()]
    if catalogs_list.__len__() == 2:
        catalog2_name = catalogs_list[0]
        catalog3_name = catalogs_list[1]
        item['catalog2Name'] = catalog2_name
        item['catalog2Id'] = md5(catalog2_name + ":2")
        item['catalog3Name'] = catalog3_name
    item['catalog3Id'] = catalog3_id
    item['catalog3Id'] = str(meta.get("catalog3Id"))
    item['catalog3Name'] = meta.get("catalog3Name")

    if sp_sku_id:
        item['supplierSkuId'] = sp_sku_id
        plat_code = None
        if item['supplierId'] == '353' or '得力' in item['supplierName']:
            plat_code = 'deli'
        item['supplierSkuCode'] = convert_id2code(plat_code, sp_sku_id)

    return item


def full_catalog(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    batch_no = meta.get('batchNo')
    catalog3_id = meta.get('catalog3Id')
    jpy = PyQuery(response.text)
    result = ItemDataSupply()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    catalog1_name = jpy('.breadcrumb strong').text().strip()
    result['catalog1Name'] = catalog1_name
    result['catalog1Id'] = md5(catalog1_name + ":1")
    catalogs_list = [x.text().replace('>\xa0', '').strip() for x in jpy('.breadcrumb span').items()]
    if catalogs_list.__len__() == 2:
        catalog2_name = catalogs_list[0]
        catalog3_name = catalogs_list[1]
        result['catalog2Name'] = catalog2_name
        result['catalog2Id'] = md5(catalog2_name + ":2")
        result['catalog3Name'] = catalog3_name
    result['catalog3Id'] = catalog3_id
    return result
